package com.dt.dubai.core.utile;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {


    // 空格键截取
    public static String clearStringEndBlank(String str) {
        char[] oldStr = str.toCharArray();
        int strlong = str.length() - 1;
        int subEndInd = 0;
        for (int i = strlong; i > 0; i--) {
            int c = oldStr[i];
//            System.out.println(c);
            if (c != 32) { // 32 空格键
                subEndInd = i;
                break;
            }
        }
        if (subEndInd == 0) {
            return "";
        } else {
            return str.substring(0, subEndInd + 1);
        }
    }

    public static void main(String[] arge) {

        System.out.println(CommonUtil.clearStringEndBlank("  saf  "));

    }


    /**
     * 判断应用是否启动完成
     *
     * @param host
     * @param port
     * @return
     */
    public static boolean isHostConnectable(String host, int port) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(host, port));
        } catch (IOException e) {
            // e.printStackTrace();
            return false;
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public static String getLangType(Locale locale) {
        // 多语言
        if ("zh_CN".equals(locale.toString())) {
            return "1";
        } else if ("en_US".equals(locale.toString())) {
            return "2";
        } else if ("ja_JP".equals(locale.toString())) {
            return "3";
        }
        return "1";
    }

    /**
     * 密码强度评分工具
     *
     * @param s
     * @return
     */
    public static int getPwdSecurityLevel(String s) {
        int len = s.length();
        int num = 0;
        int lowerCase = 0;
        int upperCase = 0;
        int ch = 0;
        int score = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c >= '0' && c <= '9') {
                num++;
            } else if (c >= 'A' && c <= 'Z') {
                upperCase++;
            } else if (c >= 'a' && c <= 'z') {
                lowerCase++;
            } else if (c >= 0x21 && c <= 0x2F || c >= 0x3A && c <= 0x40
                    || c >= 0X5B && c <= 0x60 || c >= 0x7B && c <= 0x7E) {
                ch++;
            }
        }

        // 一、密码长度
        if (len <= 4) {
            score += 5;
        } else if (len <= 7) {
            score += 10;
        } else {
            score += 25;
        }

        // 二、字母
        if (lowerCase > 0) {
            score += 10;
        }

        if (upperCase > 0) {
            score += 10;
        }

        // 三、数字
        if (num == 1) {
            score += 10;
        } else if (num > 1) {
            score += 20;
        }

        // 四、符号
        if (ch == 1) {
            score += 10;
        } else if (ch > 1) {
            score += 25;
        }

        if (num > 0 && (upperCase > 0 || lowerCase > 0)) {
            score += 2;
            if (ch > 0) {
                score += 1;

                if (upperCase > 0 && lowerCase > 0) {
                    score += 2;
                }
            }
        }
        System.out.println(score);
//        if (score >= 90) {
//            return "VERY_SECURE";
//        } else if (score >= 80) {
//            return "SECURE";
//        } else if (score >= 70) {
//            return "VERY_STRONG";
//        } else if (score > 60) {
//            return "STRONG";
//        } else if (score >= 50) {
//            return "AVERAGE";
//        } else if (score >= 25) {
//            return "WEAK";
//        } else {
//            return "VERY_WEAK";
//        }
        return score;
    }

    /**
     * 判断userAgentß
     *
     * @param request
     */
    public static String getPlatform(HttpServletRequest request) {

        /**User Agent中文名为用户代理，简称 UA，它是一个特殊字符串头，使得服务器
         能够识别客户使用的操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、浏览器语言、浏览器插件等*/
        String agent = request.getHeader("user-agent");
        //客户端类型常量
        String type = "pc";
        if (agent.contains("iPhone") || agent.contains("iPod") || agent.contains("iPad")) {
            type = "ios";
        } else if (agent.contains("Android") || agent.contains("Linux")) {
            type = "apk";
        } else if (agent.indexOf("micromessenger") > 0) {
            type = "wx";
        } else {
            type = "pc";
        }
        return type;
    }

    /**
     * 获取访问这的真实IP地址
     *
     * @param request
     * @return
     */
    public static String getRequestIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }

        }

        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 通过编译文件路径获取程序运行目录
     *
     * @param cls 类的编译文件所在位置
     * @return
     */
    public static String getAppPath(Class cls) {
        if (cls == null)
            throw new IllegalArgumentException("参数不能为空！");
        ClassLoader loader = cls.getClassLoader();
        String clsName = cls.getName() + ".class";
        Package pack = cls.getPackage();
        String path = "";
        if (pack != null) {
            String packName = pack.getName();
            clsName = clsName.substring(packName.length() + 1);
            if (packName.indexOf(".") < 0)
                path = packName + "/";
            else {
                int start = 0, end = 0;
                end = packName.indexOf(".");
                while (end != -1) {
                    path = path + packName.substring(start, end) + "/";
                    start = end + 1;
                    end = packName.indexOf(".", start);
                }
                path = path + packName.substring(start) + "/";
            }
        }
        java.net.URL url = loader.getResource(path + clsName);
        String realPath = url.getPath();
        int pos = realPath.indexOf("file:");
        if (pos > -1) realPath = realPath.substring(pos + 5);
        pos = realPath.indexOf(path + clsName);
        realPath = realPath.substring(0, pos - 1);
        if (realPath.endsWith("!"))
            realPath = realPath.substring(0, realPath.lastIndexOf("/"));
        try {
            realPath = java.net.URLDecoder.decode(realPath, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return realPath;
    }

    /**
     * 保存文件
     *
     * @param basepath 文件保存路径
     * @param file     文件
     * @param filename 保存的文件名
     * @return
     */
    public static boolean saveFile(String basepath, MultipartFile file, String filename) {
        if (file == null) {
            return false;
        }
        InputStream in = null;
        OutputStream out = null;
        String path = "";
        try {
            File dir = new File(basepath);
            if (!dir.exists())
                dir.mkdirs();
            path = dir.getAbsolutePath() + File.separator + filename;
            File serverFile = new File(path);
            //如果文件不存在则写入文件
            if (!serverFile.exists()) {
                in = file.getInputStream();
                out = new FileOutputStream(serverFile);
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = in.read(b)) > 0) {
                    out.write(b, 0, len);
                }
                out.close();
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean isDate(String strDate) {
        Pattern pattern = Pattern
                .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
        Matcher m = pattern.matcher(strDate);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isNumber(String str) {
        //采用正则表达式的方式来判断一个字符串是否为数字，这种方式判断面比较全
        //可以判断正负、整数小数

        boolean isInt = Pattern.compile("^-?[1-9]\\d*$").matcher(str).find();
        boolean isDouble = Pattern.compile("^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$").matcher(str).find();

        return isInt || isDouble;

    }
}
